﻿using ArticleandSiteData;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
using Windows.Web.Http.Headers;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace SplitViewOptions
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class UploadpicPage : Page
    {
        public UploadpicPage()
        {
            openPicker.FileTypeFilter.Add(".jpeg"); //过滤文件类型，目前只支持jpg, png,选择其他文件会报错。
          openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".png");
           // openPicker.FileTypeFilter.Add(".docx");
            this.InitializeComponent();
        }
        private void uppic(object sender, RoutedEventArgs e)
        {
            UploadPicture();
        }
        FileOpenPicker openPicker = new FileOpenPicker();//打开文件选择器。
        private static MemoryStream GenerateSampleStream(int size)
        {
            // Generate sample data.
            byte[] subData = new byte[size];
            for (int i = 0; i < subData.Length; i++)
            {
                subData[i] = 64; // '@'
            }

            return new MemoryStream(subData);
        }
        private async void sharepic(string url,string name)
            {
            ring.IsActive = true;
            string api = "https://api.bmob.cn/1/classes/sharepictable";
            Dictionary<string, string> userdic = new Dictionary<string, string>();
            userdic.Add("picurl", url);        
           

        
            userdic.Add("pictitle", titlebox.Text);
            userdic.Add("weburl", App.Currenturl.AbsoluteUri);
            userdic.Add("pictags",BOX1.Text );

            //userdic.Add("mainwebspace", mainwebspacebox.Text);
            //userdic.Add("likesbox", likesbox.Text);
            //userdic.Add("introducebox", introducebox.Text);

            string jsonstrdic = RequestHelper.DictionaryTojsonstr(userdic);
            var responce = await BmobWebsiteData.AddoneWebsite<object>(api, jsonstrdic);
            if (responce.StatusCode == System.Net.HttpStatusCode.Created)
            {
                ring.IsActive = false;
                await App.showmessage("分享成功");
             
                //  MessageDialog one = new MessageDialog("注册成功,请登录");
                //await  one.ShowAsync();
                // registerbrn.IsEnabled = true;
            }
            else
            {
                ring.IsActive = false;
                await App.showmessage("分享失败");
                // MessageDialog one = new MessageDialog("注册失败");
                //await one.ShowAsync();
                // registerbrn.IsEnabled = true;
            }
        }
        public async void UploadPicture()
        {
            if (FilePicture == null) return;
            var stream =  await  FilePicture.OpenReadAsync();
            Stream stream1 = await FilePicture.OpenStreamForReadAsync();
            string requesturl = "https://api.bmob.cn/2/files/" + FilePicture.Name;
            ring.IsActive = true;
            ulong size = stream.Size;
            Uri uri = new Uri(requesturl);
           // const int contentLength = 1000;
          //  Stream stream2 = GenerateSampleStream(contentLength);
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            httpClient.DefaultRequestHeaders.Add("X-Bmob-REST-API-Key", App.Restkeyid);
            httpClient.DefaultRequestHeaders.Add("X-Bmob-Application-Id", App.Applicationid);
            //httpClient.DefaultRequestHeaders.Add("Content-Type", "application/x-jpg");
            var inputStream = stream.GetInputStreamAt(0);
            //Stream mear = inputStream.AsStreamForRead();
            //HttpContent content = new StreamContent(mear);
            //content.Headers.ContentType = new MediaTypeHeaderValue("application/x-jpg");
         
            //System.Net.Http.HttpResponseMessage response = await client.PostAsync(requesturl, content);
          

            HttpStreamContent streamContent = new HttpStreamContent(stream1.AsInputStream());
            streamContent.Headers.ContentType = new HttpMediaTypeHeaderValue("image/jpeg");
            Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri);
            request.Content = streamContent;

            // Do an asynchronous POST.
            Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request);
           
          
            if (response.StatusCode ==HttpStatusCode.Ok)
            {
                uploadedImage.Source = null;
                ring.IsActive = false;
                string content = response.Content.ToString();
                upobject resualist = (upobject)JsonConvert.DeserializeObject(content, typeof(upobject));
                sharepic(resualist.url, resualist.filename);
                await App.showmessage("上传成功");
              
                //  MessageDialog one = new MessageDialog("注册成功,请登录");
                //await  one.ShowAsync();
                // registerbrn.IsEnabled = true;
            }
            else
            {
                ring.IsActive = false;
                await App.showmessage("上传失败");
               
                // MessageDialog one = new MessageDialog("注册失败");
                //await one.ShowAsync();
                // registerbrn.IsEnabled = true;
            }
            //using (var inputStream = stream.GetInputStreamAt(0))
            //{
            //    // We'll add more code here in the next step.
            //    if (FilePicture == null) return;
            //    var myClient = new System.Net.Http.HttpClient();
            //    var myRequest = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, requesturl);
            //    // HttpContent content = new StringContent(@"{ ""url"": ""http://cili006.com/""}");
            //    var mear = inputStream.AsStreamForRead();
            //    //mear.Position = 0;
            //    HttpContent content = new StreamContent(mear);
            // Stream te=await   content.ReadAsStreamAsync();

            //    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-jpg");
            //    // Send a request asynchronously continue when complete 
            //    myRequest.Content = content;

            //    //myRequest.Version = Version.Parse("1.1");
            //    myRequest.Headers.Add("X-Bmob-Application-Id", App.applicationid);
            //    myRequest.Headers.Add("X-Bmob-REST-API-Key", App.restkeyid);
            //   // myRequest.Headers.Add("Content-Type", "application/x-jpg");
            //    //HttpContent content= 
            //    //myRequest.Content=
            //    //// This property represents the client preference for the HTTP protocol version.
            //    //// The default value for UWP apps is 2.0.
            //    //Debug.WriteLine(myRequest.Version.ToString());
            //    var response = await myClient.PostAsync(requesturl, content);
            //}

            // return response;
        }
        StorageFile FilePicture = null;
        private async void chousepic(object sender, RoutedEventArgs e)
        {
             FilePicture = await openPicker.PickSingleFileAsync();
            if (FilePicture == null) return;
            if (FilePicture != null)
            {
                // Application now has read/write access to the picked file 
              
                // Open a stream for the selected file. 
                // The 'using' block ensures the stream is disposed 
                // after the image is loaded. 
                using (Windows.Storage.Streams.IRandomAccessStream fileStream =
                    await FilePicture.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    // Set the image source to the selected bitmap. 
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(fileStream);
                    uploadedImage.Source = bitmapImage;
                }
            }
      
    }
    }
    public class upobject
    {
        public string filename { get; set; }
        public string url { get; set; }
        public string cdn { get; set; }
    }
}
